package cn.com.duiba.millionaire.center.spider.common;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.SpiderListener;
import us.codecraft.webmagic.monitor.SpiderMonitor;
import us.codecraft.webmagic.monitor.SpiderStatus;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by sunchangji on 2018/6/5.
 */
public class EnhanceSpider extends Spider {

    private static Logger log = LoggerFactory.getLogger(EnhanceSpider.class);
    private SpiderStatus spiderStatus;

    public EnhanceSpider(PageProcessor pageProcessor) {
        super(pageProcessor);
        List<SpiderListener> listeners = new ArrayList<>();
        SpiderMonitor.MonitorSpiderListener monitorSpiderListener = SpiderMonitor.instance().new MonitorSpiderListener();
        listeners.add(monitorSpiderListener);
        this.setSpiderListeners(listeners);
        spiderStatus = new SpiderStatus(this, monitorSpiderListener);
    }

    @Override
    protected void onError(Request request) {
        super.onError(request);
        log.error("---爬取【"+ request.getUrl()  + "】错误---");
    }

    @Override
    protected void onSuccess(Request request) {
        super.onSuccess(request);
    }

    @Override
    public void close() {
        super.close();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        EnhanceSpider mySpider = (EnhanceSpider) o;

        return new EqualsBuilder()
                .append(this.getUUID(), mySpider.getUUID())
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(this.getUUID())
                .toHashCode();
    }
}
